<template>
  <el-container>
    <el-main>
      <el-form ref="orderForm" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">盘点信息</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="7">
            <el-form-item label="盘点门店">
              <el-select style="width:100%"  v-model="shopName" value-key="id" placeholder="请选择门店" @change="changeShop" >
                <el-option v-for="item in shops" :label="item.name" :value="item" ></el-option>
<!--                <el-option style="background-color: #f9f9f9;text-align: center;" key="#" label="-&#45;&#45; 新增门店 -&#45;&#45;"-->
<!--                            value="#"></el-option>-->
              </el-select>

            </el-form-item>
          </el-col>
          <!--<el-col :span="7">-->
            <!--<el-form-item label="所属部门">-->
              <!--<el-input v-model="officeName" suffix-icon="el-icon-arrow-down" @focus="dialogShow"/>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="7">
            <el-form-item label="盘点日期">
              <el-date-picker
                style="width: 100%"
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="盘点人员">
              <el-select style="width: 150px" v-model="operatorName" filterable placeholder="盘点人"
                         @change="selectSysEmployee">
                <el-option
                  v-for="item in sysEmployeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="7">
            <el-form-item label="留言备注">
              <el-input v-model="form.memo"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">盘点明细</span>
          <div style="display: flex;padding-top: 10px;padding-bottom: 10px">
            <el-input v-model="query.sn" placeholder="请输入货号" @change="queryClick"></el-input>
<!--            <el-button style="margin-left: 20px;margin-right: 10px" type="primary" icon="el-icon-plus"-->
<!--                       @click="moreProductClick">添加商品-->
<!--            </el-button>-->
          </div>
        </div>
        <!--商品规格-->
        <el-table
          :data="productList"
          border
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名"
            >
            <template slot-scope="{row}">
              <div style="position: relative">
                <i class="el-icon-arrow-down" style="position: absolute;bottom: 11px;color: #CCCC;right: 8px;z-index: 99;"></i>
                <el-select style="width: 100%" v-model="row.name" filterable placeholder="请选择" remote :remote-method="productMethod" @change="selectClick" @focus="tableClick(row)">
                  <el-option
                    v-for="(item,index) in listForm"
                    :key="index"
                    :label="item.name"
                    style="width:650px"
                    :value="index"
                  >
                    <div style="display: flex">
                      <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                      <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                      <div style="width: 200px;">
                        <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                      </div>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toAddProduct">搜索商品</div>
                    <div class="elOption1" @click="toSearchProduct">新增商品</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            align="center"
            max-width="300"
          >
            <template slot-scope="{row}">
              <span>{{row.spec}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="150"
          >
            <template slot-scope="{row}">
              <span>{{row.sn}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            width="100"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="账面库存"
            width="100"
            prop="bookQuantity"
           >
          </el-table-column>
          <el-table-column
            label="实际库存"
            width="100"
            align="right"
          >
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.physicalQuantity"/>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            width="100"
            label="操作"
          >
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <a @click="delProduct(row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
<!--        <el-button type="primary" style="margin-top: 20px" @click="addProduct">添加规格</el-button>-->
        <div style="display: flex;justify-content: flex-end">
          <el-button type="success" v-permission="['check.audit']" style="margin-top: 20px" :loading="clickedConfirm" @click="saveAndConfirmClick('orderForm')">保存并确认</el-button>
          <el-button  style="margin-top: 20px" :loading="clicked" @click="saveClick('orderForm')">保存至草稿</el-button>
        </div>
      </el-form>
      <el-dialog
        title="新增商品"
        :visible.sync="procuctVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="productClose">
        <div style="height: 65vh;overflow: auto;position: relative;">
          <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="orderVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="orderClose">
        <div style="position: relative;">
          <productTable ref="productList" @orderClose="orderClose" @doubleClick="doubleClick" @addClick="addClick"></productTable>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="queryType"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="queryClose">
        <div style="position: relative;height: 60vh;overflow: auto">
           <productRadio :findByList="findByList" @findByClick="findByClick"></productRadio>
        </div>
      </el-dialog>
      <el-dialog
        title="新增店铺"
        :visible.sync="shopVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="shopClose">
        <div style="height: 65vh;overflow: auto;position: relative;">
          <shopAdd ref="shop"></shopAdd>
          <el-button type="primary" style="margin-top: 20px"  @click="saveShop()">保存</el-button>
        </div>
      </el-dialog>
      <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
    </el-main>
  </el-container>
</template>
<script>
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import { mapGetters } from 'vuex'
  import shopAdd from '../shop/add'
  import {list as shopList} from '../../api/shop'
  import {EventBus} from '@/api/eventBus'
  import {list as productList} from '@/api/product'
  import {save, saveAndConfirm, getBookQuantity} from '@/api/check'
  import utils from '../../utils/utils.js'
  import productAdd from '@/views/product/add'
  import {list as sysEmployeeList} from '@/api/sysEmployee'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '../../components/ProductList/productList'
  import OfficeDialog from '@/components/OfficeDialog'
  import {findBySn} from "../../api/product";
  import productRadio from './components/productRadio'

  export default {
    directives: {elDragDialog,permission},
    name: 'check-add',
    data() {
      return {
        shopVisible:false,
        sysEmployeeList:[],
        clicked: false, // 按钮防双击
        shopName:'',
        form: {
          shopId:'',
          orderDate: new Date(),
          operatorId: '',
          officeId: '',
          memo: '',
        },
        shops:[],
        productList: [],
        query: {
          sn: ''
        },
        keyword: {
          sn: ''
        },
        listForm: [],
        clickedConfirm:false,
        tableIndex: '',
        procuctVisible: false,
        orderVisible: false,
        productType: 'order',
        chooseOrderName: '',
        operatorName: '',
        officeName: '',
        rules: {
          shopId: [
            {required: true, message: '盘点仓库不能为空', trigger: 'blur'},
          ],
          orderDate: [
            {required: true, message: '盘点日期不能为空', trigger: 'blur'},
          ]
        },
        queryType:false,
        findByList:[],
      }
    },
    created() {
      if (this.employee != null) {
        this.form.operatorId = this.employee.id;
        this.form.officeId = this.employee.officeId;
        this.officeName = this.employee.officeName;
        this.operatorName = this.employee.name;
      }
      this.loadSysEmployee()
      this.loadShop()
      this.loadlist('');
    },
    computed: {
      ...mapGetters([
        'employee'
      ])
    },
    components: {
      productAdd, productTable, OfficeDialog ,productRadio,shopAdd
    },
    methods: {
      changeShop(val){
       if (val.id!=this.form.shopId){
         this.form.shopId=val.id;
         this.shopName=val.name;
         this.productList=[];
       }
       this.addProduct()
      },
      saveShop(){
        this.$refs.shop.saveshop()
      },
      productMethod(query){
        this.loadlist(query)
      },
      shopClose(){
        this.shopVisible=false
      },
      loadSysEmployee( ) {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageSize',100)
        sysEmployeeList(params).then(response => {
          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //删除商品列表
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }
        this.addProduct()
      },
      //新增商品
      addProduct() {
        var _this = this
        if (_this.productList.length == 0) {
          _this.productList.push({
            productId: '',
            name: '',
            sn: '',
            physicalQuantity: '',
            bookQuantity: '',
            spec: '',
            unit: ''
          })
        } else {
          if (_this.productList[_this.productList.length - 1].productId!= '') {
            _this.productList.push({
              productId: '',
              name: '',
              sn: '',
              physicalQuantity: '',
              bookQuantity: '',
              spec: '',
              unit: ''
            })
          }
        }
      },
      loadShop(){
        shopList().then(res=>{
          this.shops=res.data.data
        })
      },
      //商品总数据
      loadlist(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.keyword.sn)
        params.append('keyword',query)
        productList(params).then(response => {
          console.log(response);
          _this.listForm = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //更多商品弹出
      moreProductClick() {
        var _this = this;
        if (this.form.shopId!=''){
          _this.orderVisible = true;
        }else{
          this.$message({
            message: '请先选择门店',
            type: 'warning'
          });
          return
        }
      },
      doubleClick(data) {
        var _this = this;

          var goodsDetails = {
            productId: data.id,
            name: data.name,
            physicalQuantity:0,
            bookQuantity: 0,
            sn: data.sn,
            price: data.price,
            orders: data.orders,
            subTotal: data.price,
            cost: data.cost,
            amountPaid: 0,
            discount: 0,
            quantity: 1,
            spec: data.spec1 ,
            unit: data.unit,
          };
          _this.productList.push(goodsDetails)

        // _this.productList.push(data)
        let params=new URLSearchParams()
        params.append('productIds',data.id)
        params.append('shopId',this.form.shopId)
        getBookQuantity(params).then(res=>{
          if (!utils.isNull(res.data)){
            var bookQuantity = 0;
            if (res.data.length>0) {
              bookQuantity = res.data[0].bookQuantity
            }
            _this.productList[this.productList.length-1].bookQuantity=bookQuantity
          }
        })
        setTimeout(()=>{
          this.searchSame();
        },500)
        this.addProduct()
      },
      addClick(data) {
        var _this = this
        console.log(data)
        let params=new URLSearchParams()
        data.forEach( item => {
          var goodsDetails = {
            productId: item.id,
            name: item.name,
            physicalQuantity:0,
            bookQuantity: 0,
            sn: item.sn,
            price: item.price,
            orders: item.orders,
            subTotal: item.price,
            cost: item.cost,
            amountPaid: 0,
            discount: 0,
            quantity: 1,
            spec: item.spec1,
            unit: item.unit
          };
          _this.productList.push(goodsDetails)
          params.append('productIds',item.id)
        });
        params.append('shopId',this.form.shopId)
        if (data.length>0){
          getBookQuantity(params).then(res=>{
            if (!utils.isNull(res.data)){
              res.data.forEach(item=> {
                for (var i=0;i<_this.productList.length;i++){
                  if (_this.productList[i].productId==item.productId) {
                    _this.productList[i].bookQuantity=item.bookQuantity
                  }
                }
              })
            }
          })
        }
        setTimeout(()=>{
          this.searchSame();
        },500)
        this.addProduct()
      },
      orderClose() {
        this.orderVisible = false;
        if ( this.productList.length>0&&this.chooseOrderName!=''){
          this.productList[this.tableIndex].name = this.chooseOrderName
        }
        this.$refs.productList.cancelClick();
      },
      //商品表下拉选择
      selectClick(index) {
        console.log(index)
        var _this = this
        if (index == '#') {
          _this.procuctVisible = true;
        } else if(index=='/') {
          this.orderVisible = true;
        }else {
            _this.productList[_this.tableIndex].productId= _this.listForm[index].id
            _this.productList[_this.tableIndex].name=_this.listForm[index].name
            _this.productList[_this.tableIndex].sn= _this.listForm[index].sn
            _this.productList[_this.tableIndex].physicalQuantity=0
            _this.productList[_this.tableIndex].bookQuantity=0
            _this.productList[_this.tableIndex].unit=_this.listForm[index].unit
            _this.productList[_this.tableIndex].spec= _this.listForm[index].spec1
            _this.productList[_this.tableIndex].quantity= 1
          let params=new URLSearchParams()
          params.append('productIds', _this.productList[_this.tableIndex].productId)
          params.append('shopId',this.form.shopId)
          getBookQuantity(params).then(res=>{
            if (!utils.isNull(res.data)){
              var bookQuantity = 0;
              if (res.data.length>0) {
                bookQuantity = res.data[0].bookQuantity
              }
              for (var i=0;i<_this.productList.length;i++){
                if (_this.productList[i].productId== _this.productList[_this.tableIndex].productId) {
                  _this.productList[i].bookQuantity=bookQuantity
                }
              }
            }
          })
        }
        this.addProduct()
      },
      //获取当前点击商品表行
      tableClick(data) {
        this.tableIndex = this.productList.indexOf(data);
        this.chooseOrderName = this.productList[this.tableIndex].name
      },
      //新增商品弹窗
      productClose() {
        this.procuctVisible = false;
        this.productList[this.tableIndex].name = this.chooseOrderName
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.productList[this.tableIndex] = data;
        this.procuctVisible = false;
      },
      searchSame(){
        let newfood = [];
        var temp = {};
        for (var i in this.productList) {
          if (this.productList[i].productId != '') {
            var key = this.productList[i].productId;
            if (temp[key]) {
              temp[key].productId = temp[key].productId;
              temp[key].quantity = 1;
              temp[key].subTotal = parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity);
              temp[key].amountPaid = temp[key].subTotal

            } else {
              temp[key] = {};
              temp[key].productId = this.productList[i].productId;
              temp[key].quantity = this.productList[i].quantity;
              temp[key].subTotal = parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity);
              temp[key].amountPaid = temp[key].subTotal
            }
            temp[key].subType = this.productList[i].subType;
            temp[key].name = this.productList[i].name;
            temp[key].sn = this.productList[i].sn;
            temp[key].price = this.productList[i].price;
            temp[key].cost = this.productList[i].cost;
            temp[key].orders = this.productList[i].orders;
            temp[key].discount = this.productList[i].discount;
            temp[key].spec = this.productList[i].spec;
            temp[key].unit = this.productList[i].unit
          }
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.productList = newfood
      },

      //订单保存
      saveClick(form) {
        const _this = this
        if (this.shopName==''){
          this.$message.error('请选择门店');
          return
        }else if(_this.operatorName==''){
          this.$message.error('请选择盘点人员');
          return
        }else if(_this.productList[0].productId==''){
          this.$message.error('请选择盘点商品');
          return
        }
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            _this.productList.forEach(function (item) {
                if (item.productId != ''){
                  var goodsDetails = {
                    productId: item.productId,
                    bookQuantity:item.bookQuantity,
                    name: item.name,
                    sn: item.sn,
                    physicalQuantity:item.physicalQuantity,
                    spec: item.spec,
                    unit:item.unit
                  };
                  itemList.push(goodsDetails)
                }
            });
            let formData = {
              shopId:_this.form.shopId,
              operatorId: _this.form.operatorId,
              orderDate: _this.form.orderDate,
              memo: _this.form.memo,
              officeId:_this.form.officeId,
              itemList: itemList,


            };
            save(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('check-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/check/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      //订单保存确认
      saveAndConfirmClick(form) {
        const _this = this
        if (this.shopName==''){
          this.$message.error('请选择门店');
          return
        }else if(_this.operatorName==''){
          this.$message.error('请选择盘点人员');
          return
        }else if(_this.productList[0].productId==''){
          this.$message.error('请选择盘点商品');
          return
        }
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            _this.clickedConfirm = true
            let itemList = [];
            _this.productList.forEach(function (item) {
              if (item.productId != '') {
                var goodsDetails = {
                  productId: item.productId,
                  bookQuantity: item.bookQuantity,
                  name: item.name,
                  sn: item.sn,
                  physicalQuantity: item.physicalQuantity,
                  spec: item.spec,
                  unit: item.unit
                };
                itemList.push(goodsDetails)
              }
            });
            let formData = {
              shopId:_this.form.shopId,
              operatorId: _this.form.operatorId,
              orderDate: _this.form.orderDate,
              memo: _this.form.memo,
              officeId:_this.form.officeId,
              itemList: itemList,

            };
            saveAndConfirm(formData).then(response => {
              _this.clickedConfirm = false;
              EventBus.$emit('check-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/check/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clickedConfirm = false
            })
          } else {
            return false
          }
        })
      },
      toAddProduct(){
        this.orderVisible = true;

      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      //会员选择
      selectSysEmployee(data) {
        this.form.operatorId = data
      },
      //  销售公司
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      dialogConfirm(val) {
        this.form.officeId = val.id;
        this.officeName = val.name
      },

      //刷新商品合计
      refreshClick() {

      },
      queryClick() {
        var _this = this
        if (this.form.shopId!=''){
          let params = new URLSearchParams();
          params.append('sn', _this.query.sn);
          findBySn(params).then(response => {
            if (response.data.products.length == 1){
              var goodsDetails = {
                productId: response.data.products[0].id,
                name: response.data.products[0].name,
                sn: response.data.products[0].sn,
                spec:response.data.products[0].spec1 + response.data.products[0].spec2,
                physicalQuantity:0,
                bookQuantity:0,
                unit:response.data.products[0].unit
              };
              _this.productList.push(goodsDetails)
              let params=new URLSearchParams()
              params.append('productIds',goodsDetails.productId)
              params.append('shopId',this.form.shopId)
              getBookQuantity(params).then(res=>{
                if (!utils.isNull(res.data)){
                  var bookQuantity = 0;
                  if (res.data.length>0) {
                    bookQuantity = res.data[0].bookQuantity
                  }
                  for (var i=0;i<_this.productList.length;i++){
                    if (_this.productList[i].productId==goodsDetails.productId) {
                      _this.productList[i].bookQuantity=bookQuantity
                    }
                  }
                }
              })
              setTimeout(()=>{
                this.searchSame();
              },500)
            }else if (response.data.products.length > 1) {
              _this.findByList = response.data.products
              _this.queryType = true
            }
            _this.addProduct()
          }).catch(error => {
            console.log('error!!')
          });
        }else{
          this.$message({
            message: '请先选择门店',
            type: 'warning'
          });
          return
        }


      },
      queryClose(){
        this.queryType = false
      },
      findByClick(data) {
        var _this = this
        let params=new URLSearchParams()
        data.forEach(function (item) {
          params.append('productIds',item.productId)
          item.bookQuantity = 0
          _this.productList.push(item)
        });
        params.append('shopId',this.form.shopId)
        getBookQuantity(params).then(res=>{
          if (!utils.isNull(res.data)){
            res.data.forEach(function (item) {
              for (var i=0;i<_this.productList.length;i++){
                if (_this.productList[i].productId==item.productId) {
                  _this.productList[i].bookQuantity=item.bookQuantity
                }
              }
            })
          }
        })
        this.queryType = false
        this.searchSame();
      },
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }

  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    padding-right: 20px;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
  .elOption1{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
</style>
